/** 加解密工具 */

const crypto = require('crypto')

const secretKey = "@#￥%……&*"

// 随机获取指定长度的盐值
module.exports.getSalt = (length = 10) => {
  return crypto.randomBytes(Math.ceil(length / 2))
    .toString('hex')
    .slice(0, length)
}

// MD5加密不带盐值
module.exports.md5 = (data) => {
  let hash = crypto.createHash('md5')
  return hash.update(data).digest('hex')
}


// MD5加密带有盐值
module.exports.md5WithSalt = (data, salt) => {
  let hash = crypto.createHash('md5')
  hash.update(data + "&" + salt)
  return hash.digest('hex')
}

// sha256加密
module.exports.sha256 = (data) => {
  let hash = crypto.createHash('sha256', secretKey)
  return hash.update(data).digest('hex')
}

// sha256加密
module.exports.sha512 = (data) => {
  let hash = crypto.createHash('sha256', secretKey)
  return hash.update(data).digest('hex')
}

// AES 加密
module.exports.aesEncrypt = (data, key) => {
  const cipher = crypto.createCipheriv('aes192', key);
  let crypted = cipher.update(data, 'utf8', 'hex');
  crypted += cipher.final('hex');
  return crypted;
}

// AES 解密
module.exports.aesDecrypt = (data, key) => {
  const decipher = crypto.createDecipheriv('aes192', key);
  let decrypted = decipher.update(data, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}



